<template>
    <div class="contract-crmContractAccount-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:contract:account:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.contractCode" placeholder="请输入合同编号" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.accountType" placeholder="请选择记账类型">
                        <el-option key="D" label="按天" value="D"></el-option>
                        <el-option key="W" label="按周" value="W"></el-option>
                        <el-option key="M" label="按月" value="M"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.reportStatus" placeholder="请选择申报状态">
                        <el-option key="0" label="未申报" value="0"></el-option>
                        <el-option key="1" label="已申报" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="search.timefield" placeholder="请选择时间" class="w100">
                        <el-option label="开始时间" value="accountStartTime"></el-option>
                        <el-option label="结束时间" value="accountEndTime"></el-option>
                        <el-option label="创建时间" value="createTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-date-picker type="month" align="right" v-model="dateData.month"  placeholder="请选择月份"></el-date-picker>
                    <!-- <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker> -->
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <!-- <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button> -->
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:contract:account:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmContractAccount()">新增</el-button>
            <el-button v-auth="'crm:contract:account:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmContractAccount()" :disabled="tableData.selections.length != 1">修改</el-button>
            <el-button v-auth="'crm:contract:account:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button>
            <el-table ref="tableCrmContractAccountRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="center" width="50" show-overflow-tooltip>
                    <template #header>
                        <!-- 使用 el-popover 包裹 el-checkbox-group -->
                        <el-popover placement="bottom-start" :width="100" trigger="click">
                            <template #reference>
                                <!-- 点击触发器：这里放置图标 -->
                                <svg-icon name="el-icon-setting" style="cursor: pointer;"></svg-icon>
                            </template>
                            <!-- el-checkbox-group 放置在此处 -->
                            <el-checkbox-group v-model="tableData.header.selections">
                                <el-checkbox v-for="item in tableData.header.data" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
                            </el-checkbox-group>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="合同编号" prop="contractCode" v-if="tableData.header.selections.includes('contractCode')" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="客户/企业" prop="customerName" v-if="tableData.header.selections.includes('customerName')" width="250" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.customerName && scope.row.enterpriseName">{{scope.row.enterpriseName}}</span>
                        <span v-if="scope.row.customerName == undefined">{{ scope.row.enterpriseName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="记账数据" prop="accounts" min-width="300" show-overflow-tooltip>
                    <template #default="scope">
                        <!-- 使用 inline-flex 布局让子元素按行排列且不换行 -->
                        <div style="white-space: nowrap; display: inline-flex; overflow-x: auto; max-width: 100%;">
                            <div v-for="(account, index) in scope.row.accounts" :key="index" class="ml5" style="vertical-align: unset;">
                                <el-popover placement="top-start" width="400" trigger="hover">
                                    <template #reference>
                                        <!-- 使用 el-tag 创建正方形格子 -->
                                        <el-tag :type="!isAfterStartTime(account) ? 'info' : account.reportStatus === '0' ? 'danger' : 'success'"
                                                style="width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                                            {{ account.periodNum }}
                                        </el-tag>
                                    </template>
                                    <!-- 提示信息内容 -->
                                    <el-descriptions :column="1">
                                        <el-descriptions-item label="操作按钮">
                                            <el-button v-auth="'crm:contract:account:info'" type="primary" :disabled="!isAfterStartTime(account)" link @click="onOpenInfoCrmContractAccount(account)">详情</el-button>
                                            <el-button v-auth="'crm:contract:account:edit'" v-if="account.reportStatus === '0'" :disabled="!isAfterStartTime(account)" type="danger" link @click="onOpenEditCrmContractAccount(account)">申报</el-button>
                                            <el-button v-auth="'crm:contract:account:edit'" v-if="account.reportStatus !== '0'" :disabled="!isAfterStartTime(account)" type="primary" link @click="onOpenEditCrmContractAccount(account)">修改</el-button>
                                            <el-button v-auth="'crm:contract:account:remove'" type="primary" :disabled="!isAfterStartTime(account)" link @click="onTabelRowDel(account)">删除</el-button>
                                            <el-button v-auth="'crm:contract:account:change'" type="primary" link @click="onOpenChangeCrmContractAccount(account)">变更</el-button>
                                        </el-descriptions-item>
                                        <el-descriptions-item label="账期序号">第 {{ account.periodNum }} 期</el-descriptions-item>
                                        <el-descriptions-item label="记账主题">{{ account.title }}</el-descriptions-item>
                                        <el-descriptions-item label="开始时间">{{ account.accountStartTime }}</el-descriptions-item>
                                        <el-descriptions-item label="结束时间">{{ account.accountEndTime }}</el-descriptions-item>
                                        <el-descriptions-item label="记账类型">
                                            <el-tag v-if="account.accountType == 'D'">按天</el-tag>
                                            <el-tag v-if="account.accountType == 'W'">按周</el-tag>
                                            <el-tag v-if="account.accountType == 'M'">按月</el-tag>
                                        </el-descriptions-item>
                                        <el-descriptions-item label="申报状态">{{ account.reportStatus == '0' ? '未申报' : '已申报' }}</el-descriptions-item>
                                        <el-descriptions-item label="税种名称">{{ account.taxation }}</el-descriptions-item>
                                        <el-descriptions-item label="开票数量">{{ account.invoiceNum }}</el-descriptions-item>
                                        <el-descriptions-item label="交付内容">{{ account.content }}</el-descriptions-item>
                                    </el-descriptions>
                                </el-popover>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmContractAccount ref="addCrmContractAccountRef" @submit="onTableSearch"/>
        <EditCrmContractAccount ref="editCrmContractAccountRef" @submit="onTableSearch"/>
        <ChangeCrmContractAccount ref="changeCrmContractAccountRef" @submit="onTableSearch"/>
        <InfoCrmContractAccount ref="infoCrmContractAccountRef"/>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Local } from '/@/utils/storage';
import AddCrmContractAccount from '/@/views/crm/contract/account/addCrmContractAccount.vue';
import EditCrmContractAccount from '/@/views/crm/contract/account/editCrmContractAccount.vue';
import InfoCrmContractAccount from '/@/views/crm/contract/account/infoCrmContractAccount.vue';
import ChangeCrmContractAccount from '/@/views/crm/contract/account/changeCrmContractAccount.vue';
import { getCrmContractAccountList, delCrmContractAccount } from '/@/api/crm/contract/account/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'crm/contract/account',
    components: { AddCrmContractAccount, EditCrmContractAccount, ChangeCrmContractAccount, InfoCrmContractAccount },
    setup() {
        const tableCrmContractAccountRef = ref();
        const addCrmContractAccountRef = ref();
        const editCrmContractAccountRef = ref();
        const infoCrmContractAccountRef = ref();
        const changeCrmContractAccountRef = ref();
        const state = reactive({
            search:{
                contractCode: undefined,
                contractName: undefined,
                accountType: undefined,
                title: undefined,
                reportStatus: undefined,
                taxation: undefined,
                timefield: 'accountStartTime',
                startTime: '',
                endTime: '',
                orderBy: 'accountStartTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [new Date(new Date().getFullYear(), new Date().getMonth(), 1), new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)],
                shortcuts: getDateRangeShortcuts(),
                month: new Date(),
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false,
                header: {
                    selections: ['contractCode', 'customerName'],
                    data: [
                        { label: '合同编号', value: 'contractCode' },
                        { label: '客户/企业', value: 'customerName' }
                    ]
                }
            }
        });

        const loadTableData = (params?: object) => {
            getCrmContractAccountList(Object.assign(state.search, params)).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmContractAccountRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            state.dateData.value = [new Date(state.dateData.month.getFullYear(), state.dateData.month.getMonth(), 1), new Date(state.dateData.month.getFullYear(), state.dateData.month.getMonth() + 1, 0)];
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [new Date(new Date().getFullYear(), new Date().getMonth(), 1), new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)];
            state.dateData.month = new Date();
            state.search.contractCode = undefined;
            state.search.contractName = undefined;
            state.search.accountType = undefined;
            state.search.title = undefined;
            state.search.reportStatus = undefined;
            state.search.taxation = undefined;
            state.search.startTime = '';
            state.search.endTime = '';
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmContractAccount = (row?: object) => {
            addCrmContractAccountRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmContractAccount = (row?: object) => {
            row = row || state.tableData.selections[0];
            editCrmContractAccountRef.value.openDialog(row);
        };
        const onOpenInfoCrmContractAccount = (row: object) => {
            infoCrmContractAccountRef.value.openDialog(row);
        };
        const onOpenChangeCrmContractAccount = (row: object) => {
            changeCrmContractAccountRef.value.openDialog(row);
        };
        const isAfterStartTime = (account) =>{
            const now = new Date();
            const start = new Date(account.accountStartTime);
            return now >= start;
        }
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的记账信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmContractAccount(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData();
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条记账信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmContractAccount([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData();
                    }
                });
            }).catch(() => {});
        };
        // 页面加载时
        onMounted(() => {
            const selections = Local.get('crm_contract_account_header_selections');
            if(selections){
                state.tableData.header.selections = selections;
            }
            loadTableData();
        });
        watch(() => state.tableData.header.selections, (selections) => {
            nextTick(() => {
                Local.set('crm_contract_account_header_selections', selections)
                tableCrmContractAccountRef.value.doLayout();
            });
        }, { deep: true });
        return {
            tableCrmContractAccountRef,
            addCrmContractAccountRef,
            editCrmContractAccountRef,
            infoCrmContractAccountRef,
            changeCrmContractAccountRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmContractAccount,
            onOpenEditCrmContractAccount,
            onOpenInfoCrmContractAccount,
            onOpenChangeCrmContractAccount,
            isAfterStartTime,
            onTabelRowsDel,
            onTabelRowDel,
            ...toRefs(state),
        };
    },
};
</script>